<template>
  <div class="srarch-result">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
      :error.sync="error"
    >
      <van-cell
        v-for="(item, index) in list"
        :key="index"
        :title="item.title"
      />
    </van-list>
  </div>
</template>

<script>
import { getSearchResult } from '@/api/search'
export default {
  name: 'SearchResult',
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      page: 1,
      perPage: 20,
      error: false
    }
  },
  methods: {
    async onLoad () {
      // 1.请求获取数据
      // 2.将数据添加到数组列表中
      // 3.将本次加载中的loading关闭
      // 4.判断是否还有数据
      //    如果呦，则更新获取下一个数据的页码
      //    如果没有，则将加载状态finished设置为结束
      try {
        const { data } = await getSearchResult({
          page: this.page,
          per_page: this.perPage,
          q: this.searchText
        })
        // console.log(data+"搜索结果");

        const { results } = data.data
        this.list.push(...results)
        this.loading = false
        if (results.length) {
          this.page++
        } else {
          this.finished = true
        }
      } catch (err) {
        this.error = true
        // 加载失败了loading关闭
        this.loading = false
        this.$toast('数据获取失败~，稍后重试！')
      }
    }
  }
}
</script>

<style>
</style>
